/*
use key light LED
*/
#include"reg52.h"

typedef unsigned char u8;//重定义数据类型
typedef unsigned int u16;

//定义独立按键控制脚
sbit KEY1=P3^1;
sbit KEY2=P3^0;
sbit KEY3=P3^2;
sbit KEY4=P3^3;
//定义一个led
sbit LED=P2^1;

//宏定义独立按键按下的键值，标记按键
#define KEYNUM1 1
#define KEYNUM2 2
#define KEYNUM3 3
#define KEYNUM4 4
#define NOKEY 0

/*
延时函数
*/
void delay_10us(u16 time)
{
	while(time)
	{
		time--;
	}
}

/*
按键扫描
*/
int keyscan()
{
	if(KEY1==0||KEY2==0||KEY3==0||KEY4==0)//任意按键按下
	{
		delay_10us(1000);//消抖
		if(KEY1==0)
			return KEYNUM1;
		else if(KEY2==0)
			return KEYNUM2;
		else if(KEY3==0)
			return KEYNUM3;
		else if(KEY4==0)
			return KEYNUM4;
	}
	else if(KEY1==1&&KEY2==1&&KEY3==1&&KEY4==1)//无按键按下
		return NOKEY;
}	

void main()
{
	int key=0;
	while(1)
	{
		key=keyscan();
		if(key==KEYNUM1)//检测按键是否按下
		{
			LED=!LED;//LED状态反转
		}
		delay_10us(50000);//延时检测，防止按键跟不上检测
	}
}